package com.itheima.my_reggie.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.my_reggie.common.Result;
import com.itheima.my_reggie.dto.DishDto;
import com.itheima.my_reggie.pojo.Category;
import com.itheima.my_reggie.pojo.Dish;
import com.itheima.my_reggie.pojo.DishFlavor;
import com.itheima.my_reggie.service.ICategoryService;
import com.itheima.my_reggie.service.IDishFlavorService;
import com.itheima.my_reggie.service.IDishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private IDishService dishService;

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IDishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

//    分页查询功能
    @GetMapping("/page")
    public Result<Page> DishPage(Integer page,Integer pageSize,String name){
        Page<Dish> dishPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper<>();
        dishWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        dishService.page(dishPage,dishWrapper);
        Page<DishDto> dishDtoPage = new Page<>();
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
        List<DishDto> dishDtoList = dishPage.getRecords().stream().map(dish -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            Category category = categoryService.getById(dish.getCategoryId());
            dishDto.setCategoryName(category.getName());
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(dishDtoList);
        return Result.success(dishDtoPage);
    }

//    新增菜品信息
    @PostMapping
    public Result<String> DishSave(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto);
        Long categoryId = dishDto.getCategoryId();
        redisTemplate.delete("dish-" + categoryId);

        return Result.success("菜品添加成功");
    }

//    查询单个菜品数据，用于菜品的更新
    @GetMapping("/{id}")
    public Result<DishDto> getByIdDish(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return Result.success(dishDto);
    }

//    更新菜品信息
    @PutMapping
    public Result<String> DishUpdate(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);

        Long categoryId = dishDto.getCategoryId();
        redisTemplate.delete("dish-" + categoryId);

        return Result.success("菜品添加成功");
    }

    //    更新菜品状态
    @PostMapping("/status/{status}")
    public Result<String> DishUpdateByIds(@PathVariable Integer status,@RequestParam List<Long> ids){
        LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Dish::getStatus,status);
        updateWrapper.in(Dish::getId,ids);
        dishService.update(updateWrapper);
        return Result.success("菜品修改成功");
    }

//    删除菜品信息
    @DeleteMapping
    public Result removeDish(@RequestParam List<Long> ids){
        dishService.removeWithDish(ids);

        redisTemplate.delete("*");
        return Result.success("菜品删除成功");
    }

    @GetMapping("/list")
    public Result<List<DishDto>> DishQueryList(Long categoryId){
        log.info("查询制定分类下的菜单列表，参数：{}",categoryId);

//        从redis中获取当前分类下的菜品数据
        List<DishDto> dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get("dish-" + categoryId);
//        如果redis中查询到菜品信息，直接返回菜品
        if(dishDtoList!=null){
            return Result.success(dishDtoList);
        }


        LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper<>();
        dishWrapper.eq(categoryId!=null,Dish::getCategoryId,categoryId)
        .eq(Dish::getStatus,1)
        .orderByDesc(Dish::getUpdateTime);
        List<Dish> dishList = dishService.list(dishWrapper);

        dishDtoList = dishList.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);

            Long dishCategoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(dishCategoryId);
                dishDto.setCategoryName(category.getName());


            //当前菜品的id
            List<DishFlavor> flavors = new ArrayList<>();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,item.getId());
            flavors = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(flavors);

            return dishDto;
        }).collect(Collectors.toList());
//        若redis中不存在数据，执行查询完成后，把查询的结果缓存在redis中
        redisTemplate.opsForValue().set("dish-" + categoryId,dishDtoList);
        return Result.success(dishDtoList);
    }
}
